<?php defined('SYSPATH') OR die('No direct access allowed.');

class Post_Model extends ORM {
    protected $has_one = array('user', 'diagram');
    protected $has_many = array('attachments', 'customvalues', 'comments');
    protected $sorting = array('date' => 'desc');

    public static $posts = array();

    public function __construct($id = NULL) {
           // load database library into $this->db (can be omitted if not required)
           parent::__construct($id);
    }

    public function __set($key, $value) {
        if ($key == 'date') {
            $value = strtotime($value);
        }
        if ($key == 'uri') {
            $value = $this->unique_uri($value);
        }
        parent::__set($key, $value);
    }

    // do the post template pre
    public function __get($key) {

        $customvalues = parent::__get('customvalues');
        foreach($customvalues as $customvalue) {
            if ($key == $customvalue->key) {
                if ($customvalue->customfield->type == 'multiple') {
                    return unserialize($customvalue->value);
                } else if ($customvalue->customfield->type == 'upload') {
                    if (defined('IN_TEMPLATE')) {
                        return url::base() . $customvalue->value;
                    } else {
                        return $customvalue->value;
                    }
                } else {
                    return $customvalue->value;
                }
            }
        }
        $value = '';
        switch($key) {
            case 'content':
                $value = parent::__get($key);
                // get the right upload file path
                $value = Arlicle::upload_file_filter($value);
                // if in template use
                if (defined('IN_TEMPLATE')) {
                    Event::run('arlicle.post.content_output_pre', $value);
                    $value = str_replace(']]>', ']]&gt;', $value);
                    //show admin edit in the web
                    if (parent::__get('id') && Auth::instance()->logged_in()) {
                        if (parent::__get('status') and parent::__get('diagram_id')) {
                            $value .= '<p>' . html::admin_anchor("/post_new/$this->id/edit?redirect_uri=" . Router::$complete_uri, T::_('Edit'), array('style'=>'color:#ff0000;')) . '</p>';
                        }

                    }
                }
            break;
            case 'thumb':
            case 'thumb_original':
                $value = '';
                $attachments = parent::__get('attachments');
                foreach($attachments as $attach) {
                    if ($attach->is_thumb) {
                        $value = $attach->filename;
                    }
                }

                if (defined('IN_TEMPLATE') and $key != 'thumb_original' and !empty($value)) {
                    $value = url::file($value);
                }
            break;
            case 'link':
                $value = parent::__get('uri');
                $key = Kohana::config('arlicle.uri_optimize');
                if ($key == 'id') {
                    $value = parent::__get('id');
                }
                $value = Kohana::config('arlicle.post_uri') . '/' . $value;

            break;
            default:
                try {
                    $value = parent::__get($key);
                } catch( Exception $e ) {
                    $value = '';
                }
            break;
        }
        return $value;
    }

    public function unique_uri($uri, $count = 1) {
        // for the second recurssion
        if ($count != 1) {
            $uri_2 = sprintf($uri, $count);
        } else {
            $uri_2 = $uri;
        }

        // check if add new or edit
        if (!empty($this->id)) {
            $post_count = $this->db->where(array('uri' => $uri_2, 'id !=' => $this->id))->count_records($this->table_name); // edit
        } else {
            $post_count = $this->db->where(array('uri' => $uri_2))->count_records($this->table_name); // add new
        }
        // if no post record use this uri, return it
        if (empty($post_count)) {
            return $uri_2;
        } else {
            // if it was been use, add_$count on it
            if ($count == 1) {
                $uri = "{$uri}-%s";
            }
            $count++;
            return $this->unique_uri($uri, $count);
        }
    }


    public static function post($args = array()) {

        $default_args = array('uri'=>'', 'id'=>0);
        if (empty($args['id']) and empty($args['uri'])) {
            // get current post
            $key = trim(URI::segment(2));
            if (strtolower(URI::segment(1)) != Kohana::config('arlicle.post_uri') or empty($key)) {
                return false;
            }
            $uri_optimize = Kohana::config('arlicle.uri_optimize');
            if ($uri_optimize == 'uri') {
                $condition = "p.uri='$key'";
            } else if ($uri_optimize == 'id') {
                $key = (int)$key;
                $condition = "p.id='$key'";
            }
        } else {
            if (!empty($args['id'])) {
                $key = (int)$args['id'];
                $condition = "p.id='$key'";
            } else if (!empty($args['uri'])) {
                $key = $args['uri'];
                $condition = "p.uri='$key'";
            }
        }

        if (empty(self::$posts[$key])) {
            $db = new Database();
            $databas_info = Kohana::config('database.default');
            $prefix = $databas_info['table_prefix'];
            $posts = $db->query("select p.*,d.type as diagram_type,d.title as diagram_title, d.content as diagram_content,d.parent_id as diagram_parent_id, d.uri as diagram_uri, d.template as diagram_template, d.metavalue as diagram_metavalue, d.date as diagram_date, d.order as diagram_order, d.status as diagram_status from {$prefix}posts as p left join {$prefix}diagrams as d on p.diagram_id=d.id where $condition limit 1");
            if (isset($posts[0])) {
                self::$posts[$key] = $posts[0];
                self::$posts[$key]->diagram_post_template = '';
                if (!empty(self::$posts[$key]->diagram_metavalue)) {
                    $metavalue = unserialize(self::$posts[$key]->diagram_metavalue);
                    if (isset($metavalue['post_template'])) {
                        self::$posts[$key]->diagram_post_template =  $metavalue['post_template'];
                    }
                }
            } else {
                self::$posts[$key] = true;
            }
        }
        return self::$posts[$key];
    }
}
